package com.mt.lulucai.util;

import com.google.gson.Gson;
import com.mt.lulucai.usbdriver.help.GlobalVariable;
import com.mt.lulucai.util.netty.NettyClient;
import com.mt.lulucai.util.netty.NettyListener;

import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.CRC32;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

public class TcpHelper {

    private GlobalVariable mGlobalVariable;
    private TcpHelper.TcpListener tTcpListener;
    private String mSendStr;

    private NettyListener mNettyListener = new NettyListener(){

        @Override
        public void onMessageResponse(Object msg) {
            ByteBuf result = (ByteBuf) msg;
            byte[] result1 = new byte[result.readableBytes()];
            result.readBytes(result1);
            result.release();
            String rcvMsg = new String(result1);
            if(tTcpListener!=null){
                tTcpListener.onSuccess(rcvMsg);
            }
        }

        @Override
        public void onServiceStatusConnectChanged(int statusCode) {
            if(!"".equals(mSendStr)){
                sendMsgToServer(mSendStr);
            }
        }
    };

    public TcpHelper(){
        mGlobalVariable = GlobalVariable.getinstance();
    }


//    public void login(final TcpHelper.TcpListener tTcpListener, final Map<String,String> paramMap) {
//        new Thread(new Runnable(){
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
//                try {
//                    String Ip = paramMap.get("Ip");
//                    String tcpPort = paramMap.get("tcpPort");
//                    Socket tcpSocket = new Socket(Ip, Integer.parseInt(tcpPort));
//                    //发送数据
//                    OutputStream OutStream = tcpSocket.getOutputStream();
//                    Map<String, Object> sendGson = new HashMap<String, Object>();
//                    long timestamp = (System.currentTimeMillis()/1000L);
//                    String security = paramMap.get("security");
//                    String tmlNo = paramMap.get("tmlNo");
//                    sendGson.put("type", 1);
//                    sendGson.put("timestamp", timestamp);
//                    sendGson.put("tmlNo", tmlNo);
//                    CRC32 crc32 = new CRC32();
//                    byte[] source = (security+timestamp+tmlNo).getBytes();
//                    sendGson.put("securityKey", Integer.toHexString((int)CRC32(source,0,source.length)));
//
//                    Map<String, Object> dataGson = new HashMap<String, Object>();
//                    dataGson.put("tmlErrorFlag", 0);
//                    dataGson.put("humanSensor", 0);
//                    dataGson.put("signal", 1);
//                    dataGson.put("tmlVersion", "tx_mt_k35_1.1_1.0");
////                    dataGson.put("lng","116.4074");
////                    dataGson.put("lat","39.9042");
//                    sendGson.put("data",dataGson);
//                    Map<String, Object> sensorGson = new HashMap<String, Object>();
//                    sensorGson.put("SPMT", 0);
//                    sensorGson.put("DCMT", 0);
//                    sensorGson.put("SS1", 0);
//                    sensorGson.put("SS2", 0);
//                    sensorGson.put("SS3", 0);
//                    sensorGson.put("SS4", 0);
//                    dataGson.put("sensor",sensorGson);
//                    String tcpString = new Gson().toJson(sendGson);
//                    tcpString = tcpString + "#llc#";
//                    tTcpListener.onFail(tcpString);
//                    OutStream.write(tcpString.getBytes());
//                    OutStream.flush();
//                    //接收数据
//                    byte[] buffer = new byte[10000];
//                    InputStream inputStream = tcpSocket.getInputStream();
//                    DataInputStream input = new DataInputStream(inputStream);
//                    int length = input.read(buffer);
//                    String Msg = new String(buffer, 0, length, "UTF-8");
//                    Msg = Msg.replaceAll("#llc#","");
//                    tTcpListener.onSuccess(Msg);
//                } catch (Exception ex) {
//                    ex.printStackTrace();
//                    tTcpListener.onFail(ex.getMessage());
//                }
//            }}).start();
//    }
    public void sendCommonRequest( final Map<String,String> paramMap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String Ip = paramMap.get("Ip");
                    String tcpPort = paramMap.get("tcpPort");
                    NettyClient nettyClient  = mGlobalVariable.getNettyClient();
                    if (nettyClient == null) {
                        nettyClient = new NettyClient(Ip, Integer.parseInt(tcpPort));
                        mGlobalVariable.setNettyClient(nettyClient);
                    }

                    String tcpString = paramMap.get("tcpString");
                    if (tcpString != null && !tcpString.contains("#llc#")) {
                        tcpString = tcpString + "#llc#";
                    }
                    sendMsgToServer(tcpString);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    if(tTcpListener!=null){
                        tTcpListener.onFail("发送失败");
                    }
                }
            }
        }).start();
    }

    private void sendMsgToServer(String sendMsg){
        NettyClient nettyClient  = mGlobalVariable.getNettyClient();
        mSendStr = "";
        if (!nettyClient.getConnectStatus()) {
            nettyClient.setListener(mNettyListener);
            nettyClient.connect();
            mSendStr = sendMsg;
        }else{
            /*
             *调用的发送。
             */
            nettyClient.sendMsgToServer(sendMsg, new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {                //4

                    } else {
                        if(tTcpListener!=null){
                            tTcpListener.onFail("发送失败");
                        }

                    }
                }
            });
        }

    }

    public TcpListener gettTcpListener() {
        return tTcpListener;
    }

    public void settTcpListener(TcpListener tTcpListener) {
        this.tTcpListener = tTcpListener;
    }

    public static long CRC32(byte[] source, int offset, int length) {
        long wCRCin = 0xFFFFFFFFL;
        long wCPoly = 0xEDB88320L;
        for (int i = offset,cnt=offset+length; i < cnt; i++) {
            wCRCin ^= ((long) source[i] & 0x000000FFL);
            for (int j = 0; j < 8; j++) {
                if((wCRCin & 0x0000001L)!=0) {
                    wCRCin >>= 1;
                    wCRCin ^= wCPoly;
                }else {
                    wCRCin >>= 1;
                }
            }
        }
        return wCRCin ^= 0xF8C85A6CL;
    }
    public interface TcpListener{
        public void onFail(String returnData);
        public void onSuccess(String returnData);
    }
}
